//
//  WBTabbarViewController.m
//  TransWB
//
//  Created by 孝飞王 on 16/12/23.
//  Copyright © 2016年 孝飞王. All rights reserved.
//

#import "WBTabbarViewController.h"
#import "WBBaseViewController.h"
#import "WBBaseNavigationController.h"
#import "WBAuthorControllerViewController.h"
//新特性 欢迎试图
#import "WBWelcomeView.h"
#import "WBNewFeatureView.h"


@interface WBTabbarViewController ()<UITabBarDelegate,UITabBarControllerDelegate>{
    NSArray *dicArray;
}
@property (nonatomic,strong)NSMutableArray *contollerArray;
@property (nonatomic,strong)UIButton *compauseBtn;//中间的按钮

@property (nonatomic, nonnull,strong)NSTimer *timer;

//是否是新版本
@property (nonatomic,assign)BOOL isNewVersion;
@end

@implementation WBTabbarViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setMainView];
    [self setUpTimer];
    self.delegate = self;
    
    //加载欢迎试图或者新特性
    [self setUpWelcomView];
    
    //注册登录通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(compauseLogin:) name:ShouldLoginSuccess object:nil];
    
}

- (void)setMainView{
  
          dicArray = @[
                    @{@"clsName":@"WBHomeViewController",
                         @"title":@"首页",
                         @"image":@"home",
                         @"visitorView":@{
                              @"title":@"关注一些人，回这里看看有什么惊喜",
                              @"imageName":@""
                              }},
                  @{@"clsName":@"WBMessageViewController",
                        @"title":@"消息",
                        @"image":@"message_center",
                        @"visitorView":@{
                            @"title":@"登录后，别人评论你的微博，发给你的消息，都会在这里收到通知",
                            @"imageName":@"visitordiscover_image_message"
                            }},
                  @{@"clsName":@"",
                        @"title":@"首页",
                        @"image":@"home",
                        @"visitorView":@{
                            @"title":@"",
                            @"imageName":@""
                            }},
                  @{@"clsName":@"WBDiscoverViewController",
                        @"title":@"发现",
                        @"image":@"discover",
                        @"visitorView":@{
                            @"title":@"登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过",
                            @"imageName":@""
                            }},
                  @{@"clsName":@"WBProfileViewController",
                        @"title":@"设置",
                        @"image":@"profile",
                        @"visitorView":@{
                            @"title":@"登录后，你的微博、相册、个人资料会显示在这里，展示给别人",
                            @"imageName":@"visitordiscover_image_profile"
                            }}
                          ];
    
    for (NSDictionary *dic in dicArray)
           [self.contollerArray addObject: [self setUpController:dic]];
    
        self.viewControllers = [self.contollerArray copy];
}

- (void)viewWillLayoutSubviews{
    
    [super viewWillLayoutSubviews];
    [self setMidButtonItem];
}

- (void)setMidButtonItem{
    
    CGFloat w = self.tabBar.bounds.size.width/self.viewControllers.count - 1;
    self.compauseBtn.frame = CGRectInset(self.tabBar.bounds, 2* w , 0);
}

//监听按钮事件
- (void ) midbtn{
    
    Class cls = NSClassFromString(@"WBTestViewController");
    UIViewController *vc = [[cls alloc]init];
    [self presentViewController:vc animated:YES completion:nil];
    
}

- (UIViewController*)setUpController:(NSDictionary*)dic{
    
    if (  [dic[@"clsName"] isEqualToString:@""]
                ||  [dic[@"title"] isEqualToString:@""]
                ||  [dic[@"image"] isEqualToString:@""]) {
        
        return [UIViewController new];
    }
    
    
    Class clasname = NSClassFromString(dic[@"clsName"]);
    WBBaseViewController *vc = [[clasname alloc  ]init];
    WBBaseNavigationController *nv = [[WBBaseNavigationController alloc] initWithRootViewController:vc];
    
    vc.tabBarItem.image = [UIImage imageNamed:
                           [NSString stringWithFormat:@"tabbar_%@", dic[@"image"]]
                           ];
    
    vc.tabBarItem.selectedImage = [[UIImage imageNamed:
                                    [NSString stringWithFormat:@"tabbar_%@_selected",dic[@"image"]]
                                    ] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    vc.tabBarItem.title = dic[@"title"];
    [vc.tabBarItem setTitleTextAttributes:
                                 @{NSForegroundColorAttributeName:[UIColor orangeColor]}
                                 forState:UIControlStateSelected];
   
    vc.navItem.title = dic[@"title"];
    vc.dataDic = dic[@"visitorView"];
    return nv;
}

#pragma mark - Lazyload

- (NSMutableArray *)contollerArray{
    
    if (_contollerArray==nil)
        _contollerArray = [NSMutableArray array];
    
    return _contollerArray;
}
- (UIButton *)compauseBtn{
    
    if (_compauseBtn == nil) {
        
        _compauseBtn = [[UIButton alloc]init];
        //设置图像
        [_compauseBtn setBackgroundImage:[UIImage imageNamed:@"tabbar_compose_button"] forState:UIControlStateNormal];
        [_compauseBtn setBackgroundImage:[UIImage imageNamed:@"tabbar_compose_button_highlighted"] forState:UIControlStateHighlighted];
        [_compauseBtn setImage:[UIImage imageNamed:@"tabbar_compose_icon_add"] forState:UIControlStateNormal];
        [_compauseBtn setImage:[UIImage imageNamed:@"tabbar_compose_icon_add_highlighted"] forState:UIControlStateHighlighted];
        
        //添加事件
        [_compauseBtn addTarget:self action:@selector(midbtn) forControlEvents:UIControlEventTouchUpInside];
        
        [self.tabBar addSubview:_compauseBtn];
        
    }
    return _compauseBtn;
}

#pragma mark - 定时器
- (void)setUpTimer{

        _timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(setTabbarBadge) userInfo:nil repeats:YES];
         _timer.fireDate = [NSDate distantPast];

}

- (void)setTabbarBadge{
    
    NSLog(@"NSTimer  定时器func");
    [[WBNetworkManager shareManager] unreadBadgetComplet:^(NSInteger count) {
        
                //设置tabbar 的未读 消息 图标
      //  self.tabBar.items[0].badgeValue  = count > 0 ? [NSString stringWithFormat:@"%ld",count] : nil;
        if (count > 0 ) {
            self.tabBar.items[0].badgeValue = [NSString stringWithFormat:@"%ld",count];
        }else{
            self.tabBar.items[0].badgeValue = nil;
        }
        
    }];
}

#pragma mark - Dealloc   注销各种通知和定时器
- (void)dealloc{
    
    if ([_timer isValid])
                  [_timer invalidate];
    [[NSNotificationCenter defaultCenter] removeObserver:ShouldLoginSuccess];

}


#pragma mark - UITabbarControllerDelegate
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    
    //中间按钮若不是baseController就不跳转
    if ([viewController isMemberOfClass:[UIViewController class]]) {
        return NO;
    }
    
    NSInteger index = [self.childViewControllers indexOfObject:viewController];
    
    
    //当前的按钮是当前的那个不是的话 就跳转到当前页 是的话跳转到顶部
    if (tabBarController.selectedIndex == 0 && tabBarController.selectedIndex == index) {
        
        WBBaseNavigationController *nav = (WBBaseNavigationController *)viewController;
        WBBaseViewController *baseviewController = nav.childViewControllers[0];
        [baseviewController.baseTabaleView setContentOffset:CGPointMake(0, -64) animated:YES];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [baseviewController loadData];
        });
    }
    
    return YES;
}
    

#pragma mark - 添加监听方法

- (void)compauseLogin:(NSNotification*)notification{
    
    //判断传过来的东西是不是又内容  如果有内容的话延迟加载  如果没有内容的话直接就跳转
    
    int64_t when = 0;
    
    //1.  判断是否有内容
    if (notification.object){
      
        //设置显示的类型
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        //[SVProgressHUD setStatus:/*SVProgressHUDMaskType*/SVProgressHUDMaskTypeClear];
        [SVProgressHUD showInfoWithStatus:@"登录已过期，请重新登录"];
        when = 2;
    }
    
    //延迟跳转
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(when * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];

        //跳转登录页面
        WBAuthorControllerViewController *author = [[WBAuthorControllerViewController alloc]init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:author];
        [self presentViewController:nav animated:YES completion:nil];
     
    });
    
    NSLog(@"我登录了啊 ");
}


#pragma mark - 新特性欢迎试图
- (void) setUpWelcomView{
    
      UIView *welcomView =   self.isNewVersion ? [WBNewFeatureView newFeatureView] : [WBWelcomeView welcomeView];
     welcomView.frame = [UIScreen mainScreen].bounds;
    [self.view addSubview:welcomView];
    
}

#pragma mark - isNewVersion
- (BOOL)isNewVersion{
    
    NSString *version = [[NSBundle mainBundle] infoDictionary] [@"CFBundleShortVersionString"];

    NSString *currentVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"CFBundleShortVersionString"];
    
    [[NSUserDefaults standardUserDefaults]  setObject:version forKey:@"CFBundleShortVersionString"];
    
    return ![version isEqualToString:currentVersion];
}


@end











